package cn.yeyiu.netonlinevideo.parser.video;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.bean.TypeData;
import cn.yeyiu.netonlinevideo.parser.Parser;
import cn.yeyiu.util.NetUtil;
import cn.yeyiu.util.bean.MediaData;
import cn.yeyiu.util.bean.VideoInfo;


/**
 * html
 */
public class YaoJinParser extends Parser {

    public YaoJinParser(SourceData source) {
        super(source);
    }

    private String getUrl(String type, int pageIndex) {
        String vtype = getArgv(type, "vtype");
        String url = source.url + vtype + "/page_" + (pageIndex + 1) + ".html";
        return NetUtil.getByUrl(url);
    }

    @Override
    public Object getBaseData(String type, int pageIndex) {
        String html = getUrl(type, pageIndex);
        return Jsoup.parse(html);
    }

    @Override
    public int getMaxCount(Object data) {
        Document document = (Document)data;
        Element ul = document.selectXpath("//div[@class='pagination xs-hide']/strong").get(1);
        String pageCount = ul.text().replace("共 ", "").replace(" 页", "");
        return Integer.parseInt(pageCount);
    }

    @Override
    public List<MediaData> getDataList(Object data, String type) {
        Document document = (Document)data;
        Elements uls = document.selectXpath("//div[@class='box movie1_list']/ul");
        if (uls.size() == 0) {
            return null;
        }
        Element ul = uls.get(0);

        List<MediaData> videoInfos = new ArrayList<>();
        MediaData mediaData;
        VideoInfo videoInfo;
        for (Element li : ul.getElementsByTag("li")) {
            videoInfo = new VideoInfo();
            mediaData = new MediaData();

            videoInfo.code = source.code;
            videoInfo.type = type;
            videoInfo.title = li.selectXpath("./li/a/h3").get(0).text();
            videoInfo.picSrc = li.selectXpath("./li/a/img").get(0).attr("src");
            videoInfo.videoSrc = videoInfo.picSrc.replace("cover.jpg", "720/play.m3u8");

            mediaData.wrap(videoInfo);
            videoInfos.add(mediaData);
        }
        return videoInfos;
    }

    @Override
    public List<TypeData> getTypeList() {
        String html = NetUtil.getByUrl(source.url+ "vod/");
        Document document = Jsoup.parse(html);
        Element ul = document.selectXpath(source.typeXpath).get(0);
        List<TypeData> types = new ArrayList<>();
        for (Element li : ul.getElementsByTag("li")) {
            types.add(new TypeData(li.text()));
        }
        return types;
    }
}
